package com.ljl.forum_1.services.impl;

import com.ljl.forum_1.common.AppResult;
import com.ljl.forum_1.common.ResultCode;
import com.ljl.forum_1.dao.UserMapper;
import com.ljl.forum_1.exception.ApplicationException;
import com.ljl.forum_1.model.User;
import com.ljl.forum_1.services.IUserService;
import com.ljl.forum_1.utils.MD5Util;
import com.ljl.forum_1.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * Keafmd
 *
 * @ClassName: UserServiceImpl
 * @Description: UserServiceImpl
 * @author: lijl
 * @date: 2025/2/6 20:34
 * @Blog: https://keafmd.blog.csdn.net/
 */
@Slf4j
@Service
public class UserServiceImpl implements IUserService {
    @Resource
    private UserMapper userMapper;

    @Transactional
    @Override
    public void createNormalUser(User user) {
        //非空校验
        if (user == null || StringUtil.isEmpty(user.getUsername()) || StringUtil.isEmpty(user.getNickname())
        || StringUtil.isEmpty(user.getPassword()) || StringUtil.isEmpty(user.getSalt())) {
            //打印日志——————有问题
            //log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 按用户名查询用户信息
        User existsUser = userMapper.selectByUserName(user.getUsername());
        // 判断用户是否存在
        if (existsUser != null) {
            //log.info(ResultCode.FAILED_USER_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }
        // 新增用户的流程，设置默认值
        user.setGender((byte) 2);
        user.setArticleCount(0);
        user.setIsAdmin((byte) 0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        // 当前日期
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);
        // 写入数据库
        int row = userMapper.insertSelective(user);
        if(row != 1) {
            //打印日志
            //log.info(ResultCode.FAILED_CREATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //打印日志
        //log.info("新增用户成功，username = " + user.getUsername() + ".");
    }

    @Override
    public User selectByUserName(String username) {
        // 非空校验
        if (StringUtil.isEmpty(username)){
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 返回查询结果
        return userMapper.selectByUserName(username);
    }

    @Override
    public User login(String username, String password) {
        // 1、非空校验
        if(StringUtil.isEmpty(username) || StringUtil.isEmpty(password)){
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        // 2、按用户名查询用户信息
        User user = selectByUserName(username);
        // 3、对查询结果做非空校验
        if(user == null) {
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        // 4、密码校验
        String encryptPassword = MD5Util.md5Salt(password, user.getSalt());
        // 5、用密文与数据库中存的密码进行比较
        if (!encryptPassword.equalsIgnoreCase(user.getPassword())) {
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        // 登录成功，返回用户信息
        return user;
    }

    @Override
    public User selectById(Long id) {
        // 1、非空校验
        if(id == null){
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        // 2、调用DAO查询数据库并获取对象
        User user = userMapper.selectByPrimaryKey(id);
        return user;
    }

    @Override
    public void addOneArticleCountById(Long id) {
        // 非空校验
        if (id == null || id <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_USER_ARTICLE_COUNT.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_ARTICLE_COUNT));
        }
        // 查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            // 打印日志
            log.warn(ResultCode.ERROR_IS_NULL.toString() + ", user id = " + id);
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        // 更新用户下的帖子数量
        User updataUser = new User();
        updataUser.setId(user.getId());
        updataUser.setArticleCount(user.getArticleCount() + 1);
        // 更新数据库
        int row = userMapper.updateByPrimaryKeySelective(updataUser);
        if (row != 1) {
            // 打印日志
            log.warn(ResultCode.FAILED.toString() + ", 受影响的行数不等于一");
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void subOneArticleCountById(Long id) {
        // 非空校验
        if (id == null || id <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_USER_ARTICLE_COUNT.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_ARTICLE_COUNT));
        }
        // 查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            // 打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString() + ", user id = " + id);
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        // 更新用户下的帖子数量
        User updataUser = new User();
        updataUser.setId(user.getId());
        updataUser.setArticleCount(user.getArticleCount() - 1);
        // 判断减1之后是否小于0
        if (updataUser.getArticleCount() < 0) {
            updataUser.setArticleCount(0);
        }
        // 更新数据库
        int row = userMapper.updateByPrimaryKeySelective(updataUser);
        if (row != 1) {
            // 打印日志
            log.warn(ResultCode.FAILED.toString() + ", 受影响的行数不等于一");
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }
}
